<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Validator;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    /**
     * Request实例
     * @var Request
     */
    protected $request;

    /**
     * 应用实例
     * @var App
     */
    protected $app;

    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app, Request $request)
    {
        $this->app     = $app;
        $this->request = $request;

        // 控制器初始化
        $this->initialize();
    }

    /**
     * 初始化
     */
    protected function initialize()
    {
        $this->user    = $this->request->user;
        $this->user_id = $this->user->id ?? 0;
    }

    /**
     * 验证数据
     * @access protected
     * @param  Request      $request          数据
     * @param  string|array $rules            表单请求名或者验证规则数组
     * @param  array        $messages         提示信息
     * @param  array        $customAttributes 是否批量验证
     */
    protected function validate(Request $request, $rules, array $messages = [], array $customAttributes = [])
    {
        $validator = Validator::make($request->all(), $rules, $messages, $customAttributes);
        if ($validator->fails()) {
            $message = $validator->errors()->first();
            $validator->validateWithBag($message);
        }
    }

    /**
     * 操作成功
     * @access protected
     * @param mixed $msg 提示信息
     * @param mixed $data 返回的数据
     * @param int $count 分页数
     * @return JsonResponse
     */
    protected function success($msg = '', $data = '', int $count = 0)
    {
        $code   = 0;
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data,
        ];
        if ($count) {
            $result['count'] = $count;
        }
        return response()->json($result);
    }

    /**
     * 操作错误
     * @access protected
     * @param mixed $msg 提示信息
     * @param int   $code 返回的数据
     * @return JsonResponse
     */
    protected function error($msg = '', $code = 1, $status = 200)
    {
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'data' => [],
        ];
        return response()->json($result, $status);
    }
}
